import time

from flask import send_file

# from fralog.kafka_logger import KafkaLogger
from result import g_ret
from copy import deepcopy
from MongoOper import *
import settings as fraplatform
from RedisOper import RedisOper
from fralog.FraLog import getFileLog
import uuid
from copy import deepcopy
import json

import logging
import logging.handlers
from settings import *
import diskcache as dc

# 设置app 为工作台
log = getFileLog().set_app('work')
LOG = log


# log = logging.getLogger('tst')  # 获取名为tst的logger
# log.addHandler(handler)  # 为logger添加handler
# log.setLevel(logging.DEBUG)


# dd = param.get('tt')
# str(uuid.uuid1()).replace("-", "")
# param['ttd'] = 'ddddd'
# log.info(param)
# ret = pagequery(fraplatform.mongo2,'surveys_collection',
#                {'$or': [{'description': None}, {'survey_id': {'$gt': 1}}]}, [('survey_id', 1)], 100, 1)
# ret = delete(fraplatform.mongo2,'pic_url_collection', {'id': '001'})
# ret = update(fraplatform.mongo2,'pic_url_collection',
# {'id': '001', 'imageurl': 'dddd'}, {'$set': {'id': '001'}}, upsert=True)
# ret = find_one(fraplatform.mongo2,'pic_url_collection', {'imageurl': 'dddd'})
# ret = insert(fraplatform.mongo2,'pic_url_collection', [{'imageurl': 'dddd2'}, {'imageurl': 'dddd3'}])
#               注意不保证事务,可能部分新增成功,后续插入不成功,返回数量0,其实已经插入前面部分
# ret = insert(fraplatform.mongo2,'pic_url_collection', {'imageurl': 'dddd2'})


def test2():
    test = deepcopy(g_ret)
    user = [{"name": "2222", "score": 33}, {"name": "2222", "score": 33}]
    return json.dumps(user)


def test(param):
    # dd = param.get('tt')
    # param['ttd'] = 'ddddd'
    # log.info(param)
    # ret = pagequery(fraplatform.mongo2,'surveys_collection',
    #                {'$or': [{'description': None}, {'survey_id': {'$gt': 1}}]}, [('survey_id', 1)], 100, 1)
    # ret = delete(fraplatform.mongo2,'pic_url_collection', {'id': '001'})
    ret = update(fraplatform.mongo, 'pic_url_collection',
                 {'id': '001', 'imageurl': 'dddd'}, {'$set': {'id': '001'}}, upsert=True)
    # ret = find_one(fraplatform.mongo2,'pic_url_collection', {'imageurl': 'dddd'})
    # ret = insert(fraplatform.mongo2,'pic_url_collection', [{'imageurl': 'dddd2'}, {'imageurl': 'dddd3'}])
    #               注意不保证事务,可能部分新增成功,后续插入不成功,返回数量0,其实已经插入前面部分
    # ret = insert(fraplatform.mongo2,'pic_url_collection', {'imageurl': 'dddd2'})
    test = {'a': '123', 'b': [1, 2, '3']}
    a = float('nan')
    ret = deepcopy(g_ret)
    log.info('into test')
    # ret = insert(fraplatform.mongo2, 'pic_url_collection', [{'imageurl': a}, test])
    # ret = pagequery(fraplatform.mongo, 't_industrytype',
    #                {'$or': [{'type': {'$regex': "大"}}, {'type': {'$regex': "类"}}]})
    # ret = insert(fraplatform.mongo, 'pic_url_collection', {'imageurl': 'dddd2'})
    log.info(ret)
    return ret


def login(param):
    log.debug('Login request')
    post_data = param
    ret = deepcopy(g_ret)
    user_id = post_data['user_id']
    pwd = post_data['pwd']
    #
    # 添加商品ID
    #
    product_id = post_data.get('product_id')
    log.write_log(msg="click login", event='click_login', user=user_id)

    check_ret, company_id = check_user_product(user_id, product_id)
    # if company_id is not None:
    #     log.debug('Company_id: %s'%company_id)
    if not check_ret:
        ret['code'] = 403
        log.write_log(msg='未购买产品，不允许登录', product_id=product_id, event="not_buy", user=user_id)
        return ret
    '''
    log.info('get session vcode', RedisOper.get(sid))
    if RedisOper.get(sid) is None:
        ret['code'] = -1
        ret['msg'] = '验证码超时!'
        self.write(json.dumps(ret))
        return

    if RedisOper.get(sid).upper() != vcode.upper():
        ret['code'] = -1
        ret['msg'] = '验证码不正确!'
        self.write(json.dumps(ret))
        return
    '''
    # 验证用户提供的登录信息是否合法
    # queryret = find_one(fraplatform.mongo, 't_user', {'user_id': user_id, 'status': 1})
    # TODO 修改为查询缓存 YSC

    cache = dc.Cache('user_cache')
    items = cache['user']
    query = None
    for item in items:
        if user_id == item['user_id']:
            query = item
            # if pwd == item['pwd']:
            #     del item['pwd']
            #     ret['code'] = 200
            #     ret['data'] = item
            #     ret['msg'] = '登录成功'
            #     return jsonify(ret)
            # else:
            #     ret['code'] = 400
            #     ret['data'] = 0
            #     ret['msg'] = '密码不匹配！'
            #     return jsonify(ret)
    # if len(queryret.get('data')) >= 1:
    #     query = queryret.get('data')[0]
    # else:
    #     query = None

    if query is None:
        ret['code'] = 402
        ret['msg'] = '未查到,密码错误'
        log.write_log(msg='wrong password', event='login_wrong_pass', user=user_id)
        # log.write_log(msg='密码错误', event='login', user=user_id, product_id=product_id, status = -3)
        return ret

    # 用户不存在
    authlist = []
    passwd = query.get('pwd')
    if passwd is None:
        ret['code'] = 402
        ret['msg'] = '数据中无该用户的记录'
        log.write_log(msg='未注册', user=user_id, event='login_not_reg')
        # log.info(msg='数据中无该用户的记录', user=user_id, product_id=product_id)
        # self.send_error(code=-1, msg='User not exists')
        return ret
    if passwd is not None and passwd == pwd:
        log.info('用户认证成功')
        # 为该用户生成Token
        # _Token_dict[user] = str(uuid.uuid4())
        token = RedisOper.RedisOper.set_token(user_id)
        sret = get_usermenu({'user_id': user_id})
        authlist = sret.get('data')
        ret['code'] = 200
        ret['msg'] = '登录成功'
        log.write_log(msg='登录成功', event='login_ok', user=user_id, product_id=product_id)
    else:
        log.info('用户密码错误或用户不存在')
        ret['code'] = 402
        ret['msg'] = '用户密码错误或用户不存在'
        log.write_log(msg='登录失败', event='login_fail', user=user_id, product_id=product_id)
        return ret
    # 用户成功通过认证，从数据库中取出用户的订单信息
    ret['company_id'] = company_id
    ret['token'] = RedisOper.RedisOper.get_token_byuserid(user_id)
    ret['data'] = [query]
    ret['userinfo'] = query
    ret['authlist'] = authlist
    # ret = insert(fraplatform.mongo2, 'pic_url_collection', [{'imageurl': 'dddd2'}, {'imageurl': 'dddd3'}])
    return ret


def check_user_product(user_id, product_id):
    '''
    检验该用户是否购买过该产品
    :param user_id: 
    :param product_id: 
    :return: 
    '''
    log.debug(msg='检查用户是否购买过该产品, product_id: %s, user_id: %s' % (product_id, user_id))
    if user_id is None or product_id is None:
        log.error('必须提供用户名及产品ID才能进行正常校验')
        return (False, None)
    # ret = find_one(fraplatform.mongo, 't_user_product', {'user_id': user_id, 'product_id': product_id})
    # TODO 产品获取缓存  product_id =
    cache = dc.Cache('product_cache')
    items = cache['product']
    query = None
    for item in items:
        if item['user_id'] == user_id and item['product_id'] == product_id:
            query = item
            company_id = item['company_id']
            log.debug('Company ID: %s' % company_id)
            return (True, company_id)
    if query is None:
        return (False, None)
    # if ret['count'] <= 0:
    #     return (False, None)
    # else:
    #     ret = ret.get('data')
    #     company_id = ret[0].get('company_id')
    #     log.debug('Company ID: %s' % company_id)
    #     return (True, company_id)


def check_token(token):
    ret = deepcopy(g_ret)
    g_login, g_user_id = RedisOper.RedisOper.get_userid_bytoken(token)
    if g_login:
        log.info('token验证成功', user=g_user_id)
        ret['code'] = 200
        return g_user_id, ret
    else:
        log.info('token验证失败', user=g_user_id)
        # self.redirect("/login")
        ret['code'] = 401
        ret['msg'] = 'token验证失败'
        return None, ret


#
# def check_token(param):
#     log.info('接收到Token验证请求')
#     ret = deepcopy(g_ret)
#     post_data = param
#     user = post_data.get('user_id')
#     token = post_data.get('token')
#     # if _Token_dict.get(user) == token:
#     if RedisOper.RedisOper.get_token_byuserid(user) == token:
#         ret['code'] = 200
#         ret['msg'] = 'Token验证成功'
#         log.info('Token验证成功')
#     else:
#         ret['code'] = 401
#         ret['msg'] = 'Token验证失败'
#         log.info('Token验证失败')
#     return ret

def get_industrytype(param):
    '''
    查询客户行业类型下拉列表
    :param param:
    :return:
    '''
    # log.debug('')
    post_data = param
    token = post_data.get('token')
    ret = deepcopy(g_ret)
    g_login, g_user_id = RedisOper.RedisOper.get_userid_bytoken(token)
    if g_login:
        log.info('token验证成功', user=g_user_id)
    else:
        log.warning('token验证失败', user=g_user_id)
        # self.redirect("/login")
        ret['code'] = 401
        ret['msg'] = 'token验证失败'
        return ret
    # 验证用户提供的登录信息是否合法
    dbret = pagequery(fraplatform.mongo, 't_industrytype')
    if dbret is None:
        dbret['code'] = 402
        dbret['msg'] = '无法查找到列表'
        log.warning('行业类型表查找为空')
        return dbret
    else:
        return dbret


def get_company(param):
    '''
    查询公司列表
    :param param:
    :return:
    '''
    # log.debug('')
    post_data = param
    token = post_data.get('token')
    ret = deepcopy(g_ret)
    g_login, g_user_id = RedisOper.RedisOper.get_userid_bytoken(token)
    if g_login:
        log.info('token验证成功')
    else:
        log.warning('token验证失败')
        # self.redirect("/login")
        ret['code'] = 401
        ret['msg'] = 'token验证失败'
        return ret
    company_name = post_data.get('company_name')
    company_type = post_data.get('company_type')
    page = 1
    pagesize = 500
    try:
        page = int(post_data.get('page'))
        pagesize = int(post_data.get('pagesize'))
    except Exception as e:
        log.info(e)
    if company_name is None:
        company_name = ''
    if company_type is None:
        company_type = ''
    queryret = find_one(fraplatform.mongo, 't_user', {'user_id': g_user_id, 'status': 1})
    query = queryret.get('data')[0]
    dbret = dict()
    if query is not None:
        if query.get('role_id') == 'admin_bd' or query.get('role_id') == 'admin':
            if company_type == '':
                dbret = pagequery(fraplatform.mongo, 'company_collection',
                                  {'company_name': {'$regex': company_name}},
                                  page=page, pagesize=pagesize)
            else:
                dbret = pagequery(fraplatform.mongo, 'company_collection',
                                  {'$and': [{'trade': {'$regex': company_type}},
                                            {'company_name': {'$regex': company_name}}]},
                                  page=page, pagesize=pagesize)
        else:
            if company_type == '':
                dbret = pagequery(fraplatform.mongo, 'company_collection',
                                  {'bd': g_user_id,
                                   'company_name': {'$regex': company_name}}, page=page, pagesize=pagesize)
            else:
                dbret = pagequery(fraplatform.mongo, 'company_collection',
                                  {'bd': g_user_id,
                                   '$and': [{'trade': {'$regex': company_type}},
                                            {'company_name': {'$regex': company_name}}]
                                   }, page=page, pagesize=pagesize)
    # 验证用户提供的登录信息是否合法
    if dbret is None:
        dbret['code'] = 402
        dbret['msg'] = '无法查找到列表'
        log.warning('查找为空')
        return dbret
    else:
        dbret['code'] = 200
        dbret['msg'] = '处理成功'
        dbret['msg_flag'] = 'ok'
        return dbret


def checkcompany_byguid(guid):
    ret = pagequery(fraplatform.mongo, table='company_collection', query={'guid': guid})
    return ret


def checkcompany_bycompanyname(company_name):
    company_namerst = company_name.replace(" ", "").replace("\t", "").strip()
    ret = pagequery(fraplatform.mongo, table='company_collection', query={'company_name': company_namerst})
    return ret


def checkuser_byuserid(user_id):
    ret = pagequery(fraplatform.mongo, table='t_user', query={'user_id': user_id})
    return ret


def get_allmenu(param):
    '''
    查询菜单列表
    :param param:
    :return:
    '''
    # log.debug('')
    post_data = param
    token = post_data.get('token')
    ret = deepcopy(g_ret)
    g_login, g_user_id = RedisOper.RedisOper.get_userid_bytoken(token)
    if g_login:
        log.info('token验证成功')
    else:
        log.warning('token验证失败')
        # self.redirect("/login")
        ret['code'] = 401
        ret['msg'] = 'token验证失败'
        return ret
    # 验证用户提供的登录信息是否合法
    dbret = pagequery(fraplatform.mongo, 't_menu', {})
    if dbret is None:
        ret['code'] = 402
        ret['msg'] = '无法查找到列表'
        log.warning('查找为空')
        return ret
    else:
        ret['code'] = 200
        ret['msg'] = '处理成功'
        ret['msg_flag'] = 'ok'
        ret['data'] = dbret
        ret['count'] = 1
        ret['total_count'] = 1
        return ret


def get_usermenu(param):
    '''
    查询用户的菜单列表
    :param param:
    :return:
    '''
    # log.debug('')
    post_data = param
    g_user_id = post_data.get('user_id')
    ret = deepcopy(g_ret)
    # 验证用户提供的登录信息是否合法
    dbret = find_one(fraplatform.mongo, 't_user', {'user_id': g_user_id})
    if dbret is None:
        ret['code'] = 402
        ret['msg'] = '无法查找到列表'
        log.info('查找为空')
        return ret
    else:
        dbret2 = find_one(fraplatform.mongo, 't_role', {'role_id': dbret['data'][0].get('role_id')})
        #
        # 需要处理角色不存在时的异常情况
        if dbret2 is None:
            ret['code'] = 500
            ret['msg'] = '无该角色'
            ret['msg_flag'] = 'error'
            ret['data'] = []
            ret['count'] = 0
            return ret
        ret['code'] = 200
        ret['msg'] = '处理成功'
        ret['msg_flag'] = 'ok'
        ret['data'] = dbret2['data'][0].get('menus')
        ret['count'] = 1
        ret['total_count'] = 1
        return ret


def insert_industrythype(param):
    '''
    新增客户行业类型
    :param param:
    :return:
    '''
    # log.debug('')
    post_data = param
    token = post_data.get('token')
    ret = deepcopy(g_ret)
    g_login, g_user_id = RedisOper.RedisOper.get_userid_bytoken(token)
    log.write_log(msg='新增客户行业类型', event='add_industry_type')
    if g_login:
        log.info('token验证成功')
        del post_data['token']
    else:
        log.info('token验证失败')
        # self.redirect("/login")
        ret['code'] = 401
        ret['msg'] = 'token验证失败'
        log.write_log(msg='因token不通过，新增客户行业类型失败', user=g_user_id, event='fail_add_industry_type')
        return ret
    # 验证用户提供的登录信息是否合法
    dbret = insert(fraplatform.mongo, 't_industrytype', post_data)
    if dbret['inserted_count'] == -1:
        dbret['code'] = 402
        dbret['msg'] = '插入行业错误,可能重复'
        log.info('插入行业错误,可能重复')
        log.write_log(msg='插入失败，新增客户行业类型失败', user=g_user_id, event='fail_add_industry_type')
        return dbret
    else:
        dbret['code'] = 200
        dbret['msg'] = '处理成功'
        dbret['msg_flag'] = 'ok'
        log.write_log(msg='新增客户行业类型成功', user=g_user_id, event='add_industry_type_ok')
        return dbret


def upsert_company(param):
    '''
    修改新增公司列表
    :param param:
    :return:
    '''
    # log.debug('')
    post_data = param
    token = post_data.get('token')
    company_info = post_data.get('companyInfo')
    ret = deepcopy(g_ret)
    g_login, g_user_id = RedisOper.RedisOper.get_userid_bytoken(token)
    if g_login:
        log.info('token验证成功')
    else:
        log.info('token验证失败')
        # self.redirect("/login")
        ret['code'] = 401
        ret['msg'] = 'token验证失败'
        return ret
    company_info['bd'] = g_user_id
    guid = company_info.get('guid')
    company_info['company_name'] = company_info['company_name'].replace(" ", "").replace("\t", "").strip()
    if guid is None:
        guid = ''
    dbret = update(fraplatform.mongo, 'company_collection', {'guid': guid, 'status': 1},
                   {'$set': company_info}, upsert=True)
    if dbret is None:
        ret['code'] = 402
        ret['msg'] = '无法查找到列表'
        log.info('查找为空')
        return ret
    else:
        dbret['code'] = 200
        dbret['msg'] = '处理成功'
        dbret['msg_flag'] = 'ok'
        return dbret


def upsert_company4bole(param):
    '''
    修改新增公司列表
    :param param:
    :return:
    '''
    log.debug('bole 新增试用公司')
    company_info = param
    ret = deepcopy(g_ret)
    company_info['bd'] = 'hr'
    guid = company_info.get('guid')
    company_info['company_name'] = company_info['company_name'].replace(" ", "").replace("\t", "").strip()
    if guid is None:
        guid = ''
    dbret = update(fraplatform.mongo, 'company_collection', {'guid': guid, 'status': 1},
                   {'$set': company_info}, upsert=True)
    if dbret is None:
        ret['code'] = 402
        ret['msg'] = '无法查找到列表'
        log.info('查找为空')
        return ret
    else:
        dbret['code'] = 200
        dbret['msg'] = '处理成功'
        dbret['msg_flag'] = 'ok'
        return dbret


def upsert_company4api(param, p_company_id=None):
    '''
    修改新增公司列表
    :param param:
    :return:
    '''
    log.debug('api 新增试用公司')
    company_info = param
    ret = deepcopy(g_ret)
    company_info['bd'] = 'hr'
    guid = company_info.get('guid')
    company_info['default_job_channel'] = [1, 1, 1]
    company_info['p_company_id'] = p_company_id
    company_info['company_name'] = company_info['company_name'].replace(" ", "").replace("\t", "").strip()
    dbret = update(fraplatform.mongo, 'company_collection', {'guid': guid, 'status': 1},
                   {'$set': company_info}, upsert=True)
    if dbret is None:
        ret['code'] = 402
        ret['msg'] = '无法查找到列表'
        log.info('查找为空')
        return ret
    else:
        dbret['code'] = 200
        dbret['msg'] = '处理成功'
        dbret['msg_flag'] = 'ok'
        return dbret


def change_pwd(param):
    '''
    修改新增公司列表
    :param param:
    :return:
    '''
    # log.debug('')
    post_data = param
    token = post_data.get('token')
    newpwd = post_data.get('newpwd')
    ret = deepcopy(g_ret)
    g_login, g_user_id = RedisOper.RedisOper.get_userid_bytoken(token)
    if g_login:
        log.info('token验证成功', user=g_user_id)
    else:
        log.info('token验证失败', user=g_user_id)
        # self.redirect("/login")
        ret['code'] = 401
        ret['msg'] = 'token验证失败'
        return ret
    dbret = update(fraplatform.mongo, 't_user', {'user_id': g_user_id},
                   {'$set': {'pwd': newpwd}}, upsert=False)
    if dbret is None:
        ret['code'] = 402
        ret['msg'] = '无法查找到列表'
        log.info('查找为空')
        log.write_log(msg='修改密码失败', user=g_user_id, product_id='bole', event='info')
        return ret
    else:
        dbret['code'] = 200
        dbret['msg'] = '处理成功'
        dbret['msg_flag'] = 'ok'
        log.write_log(msg='修改密码成功', user=g_user_id, product_id='bole', event='info', status=1)
        return dbret


def del_company(param):
    '''
    修改新增公司列表
    :param param:
    :return:
    '''
    # log.debug('')
    post_data = param
    token = post_data.get('token')
    guid = post_data.get('guid')
    ret = deepcopy(g_ret)
    g_login, g_user_id = RedisOper.RedisOper.get_userid_bytoken(token)
    if g_login:
        log.info('token验证成功')
    else:
        log.info('token验证失败')
        # self.redirect("/login")
        ret['code'] = 401
        ret['msg'] = 'token验证失败'
        return ret
    if guid is None:
        guid = ''
    dbret = delete(fraplatform.mongo, 'company_collection', {'guid': guid})
    if dbret is None:
        ret['code'] = 402
        ret['msg'] = '无法查找到列表'
        log.info('查找为空')
        return ret
    else:
        dbret['code'] = 200
        dbret['msg'] = '处理成功'
        dbret['msg_flag'] = 'ok'
        return dbret


@app.route("/test1", methods=['GET', 'POST'])
@verify_times
# @verify_token
def lg_test1():
    # time.sleep(10)
    test = deepcopy(g_ret)
    user = [{"name": "2222", "score": 33}, {"name": "2222", "score": 33}]
    return json.dumps(user)


@app.route("/test2", methods=['GET', 'POST'])
@verify_token
def lg_hello2():
    param = get_param(request)

    # j = request.get_json()
    # print(j)
    # data = json.loads(j.decode('utf-8'))
    # print(data)
    ret = test(param)
    return json.dumps(ret)


@app.route('/user', methods=['GET', 'POST'])
@app.route('/user/<string:name>', methods=['GET', 'POST'])
def lg_user(name=None):
    ret = deepcopy(g_ret)
    if name is None:
        users = mongo.db.user_collection.find()
        user_list = []
        for user in users:
            user.pop('_id')
            user_list.append(user)
        ret['data'] = user_list
        return json.dumps(ret)
    else:
        user = mongo.db.user_collection.find_one({'name': name})
        if user is not None:
            user.pop('_id')
            ret['data'] = [user]
            return json.dumps(ret)
        else:
            return ret


# @app.route('/<pathfile>')
# @allow_cross_domain
# def rootsendfile(pathfile):
#     resp = make_response(send_file("static/" + pathfile))
#     resp.headers["Content-Disposition"] = "attachment; filename=" + pathfile + ";"
#     return resp


# @app.route('/init')
# def init():
#     # pymongo.collection.Collection('flask', 'users', create=True)
#     return 'Init Successful'

@app.route("/testlogin", methods=['GET', 'POST'])
def lg_testlogin():
    ret = deepcopy(g_ret)
    return json.dumps(ret)


@app.route("/check_token", methods=['GET', 'POST'])
@verify_token
def lg_check_token():
    '''
    验证登录token是否正确
    输入token
    返回 ret集合,其中code=401则验证失败,200成功

    :return:
    '''
    param = get_param(request)
    g_user_id, ret = check_token(param)
    return json.dumps(ret)


@app.route("/login", methods=['GET', 'POST'])
def lg_login_in():
    '''
    验证登录请求
    输入:user_id , pwd
    返回:ret集合,成功ret.code=200,ret.token返回token
    :return:
    '''
    param = get_param(request)
    ret = login(param)
    product_id = param.get('product_id')
    app = ''
    event = ''
    print(product_id)
    if product_id == 'hr':
        app = 'p_bole'
        event = 'b_login'
    else:
        app = 'p_aggent'
        event = 'a_login'
    # log.write_log(msg='/login:登录', event='api_call', user=param.get('user_id'))
    # KafkaLogger().log_event(event=event, app=app, user=param.get('user_id'), level='info', msg=str(product_id) + '产品登录',
    #                         status='200')
    return json.dumps(ret)


@app.route("/get_industrytype", methods=['GET', 'POST'])
@verify_token
def lg_get_industrytype():
    '''
    获得行业类型列表
    输入token
    返回ret集合,其中ret.data=[] 数据行集合,ret.code=402则表示查找失败为空
    :return:
    '''
    log.write_log(msg='/get_industrytype:获取行业类型列表', event='api_call')
    param = get_param(request)
    ret = get_industrytype(param)
    return json.dumps(ret)


@app.route("/get_company", methods=['GET', 'POST'])
@verify_token
def lg_get_company():
    '''
    获取公司列表
    输入(token默认输入):company_name company_type 两个可不填
    返回:ret集合,admin_bd角色返回所有公司列表,普通人员返回自己公司列表
    :return:
    '''
    log.write_log(msg='/get_company:获取公司列表', event='api_call')
    param = get_param(request)
    ret = get_company(param)
    return json.dumps(ret)


@app.route("/get_allmenu", methods=['GET', 'POST'])
@verify_token
def lg_get_allmenu():
    '''
    获取菜单列表
    输入(token默认输入):
    返回:ret集合
    :return:
    '''
    param = get_param(request)
    ret = get_allmenu(param)
    return json.dumps(ret)


@app.route("/get_usermenu", methods=['GET', 'POST'])
@verify_token
def lg_get_usermenu():
    '''
    获取这个用所属角色的菜单列表
    输入(token默认输入):
    返回:ret集合,ret.code=200,ret.data=[菜单列表]
    类似 [
        "customerManagement",
        "customerInformation",
        "WechatManagement"
    ]
    :return:
    '''
    log.write_log(msg='/get_usermenu:获取角色菜单列表', event='api_call')
    param = get_param(request)
    ret = get_usermenu(param)
    return json.dumps(ret)


@app.route("/insert_industrythype", methods=['GET', 'POST'])
@verify_token
def lg_insert_industrythype():
    '''
    新增行业类型
    输入(token默认输入):
    返回:ret集合,ret.code=200
    :return:
    '''
    log.write_log(msg='/insert_industrythype:插入行业类型', event='api_call')
    param = get_param(request)
    ret = insert_industrythype(param)
    return json.dumps(ret)


@app.route("/upsert_company", methods=['GET', 'POST'])
@verify_token
def lg_upsert_company():
    '''
    新增或更新公司信息,没有则新增
    输入(token默认输入): companyInfo={} 输入公司信息对象
    返回:ret集合,ret.code=200
    :return:
    '''
    try:
        log.write_log(msg='/upsert_company:更新公司信息', event='api_call')
        param = get_param(request)
        ret = upsert_company(param)
        return json.dumps(ret)
    except Exception as e:
        print(e)
        pass


@app.route("/upsert_company4bole", methods=['GET', 'POST'])
def lg_upsert_company4bole():
    '''
    新增或更新bole公司信息,没有则新增
    输入(token默认输入): companyInfo={} 输入公司信息对象
    返回:ret集合,ret.code=200
    :return:
    '''
    try:
        log.write_log(msg='/upsert_company4bole:新增或更新', event='api_call')
        LOG.debug('新增或更新BOLE公司信息')
        param = get_param(request)
        if param.get('token') != 'tokenhuayuan':
            return json.dumps(g_ret)
        del param['token']
        print(param)
        ret = upsert_company4bole(param)
        return json.dumps(ret)
    except Exception as e:
        print(e)
        pass


@app.route("/upsert_company4api", methods=['GET', 'POST'])
def lg_upsert_company4api():
    '''
    新增或更新公司信息,没有则新增 api
    输入(token默认输入): companyInfo={} 输入公司信息对象
    返回:ret集合,ret.code=200
    :return:
    '''
    try:
        log.write_log(msg='/upsert_company4api:新增或更新', event='api_call')
        LOG.debug('新增或更新公司信息api')
        error_ret = deepcopy(g_ret)
        param = get_param(request)
        appkey = str(param.get('appkey'))
        f_company_id = None
        if appkey in APP_KEY_LIST:
            f_company_id = appkey.split('_')[0]
        else:
            error_ret['msg'] = 'appkey fail'
            error_ret['code'] = 401
            return json.dumps(error_ret)
        del param['appkey']
        print(param)
        user_id = param.get('user_id')
        company_id = param.get('guid')
        company_name = param.get('company_name')
        if checkuser_byuserid(user_id)['count'] > 0:
            error_ret['msg'] = 'userid is duplication'
            error_ret['code'] = 402
            return json.dumps(error_ret)
        elif checkcompany_byguid(company_id)['count'] > 0:
            error_ret['msg'] = 'company_id is duplication'
            error_ret['code'] = 403
            return json.dumps(error_ret)
        elif checkcompany_bycompanyname(company_name)['count'] > 0:
            error_ret['msg'] = 'company_name is duplication'
            error_ret['code'] = 404
            return json.dumps(error_ret)
        else:
            ret = upsert_company4api(param, p_company_id=f_company_id)
            return json.dumps(ret)
    except Exception as e:
        print(e)
        pass


@app.route("/del_company", methods=['GET', 'POST'])
@verify_token
def lg_del_company_():
    '''
    删除公司信息
    输入(token默认输入): guid 根据guid删除信息
    返回:ret集合,ret.code=200
    :return:
    '''
    try:
        log.write_log(msg='/del_company:删除公司', event='api_call')
        param = request.values.to_dict()
        # param = json.loads(data.decode('utf-8'))
        log.info(param)
        ret = del_company(param)
        return json.dumps(ret)
    except Exception as e:
        log.info(e)
        pass


@app.route("/fail", methods=['GET', 'POST'])
def lg_retrun_fail():
    '''
    测试接口
    输入: 无
    返回:ret集合,ret.code=401
    :return:
    '''
    ret = deepcopy(g_ret)
    ret['code'] = 401
    ret['msg'] = 'token验证失败'
    return json.dumps(ret)


@app.route("/update_password", methods=['GET', 'POST'])
@verify_token
def lg_update_password():
    '''
    修改密码
    输入(token默认输入),newpwd
    返回:ret集合,ret.code=200
    :return:
    '''
    try:
        log.write_log(msg='/update_password:更新密码', event='api_call')
        param = get_param(request)
        ret = change_pwd(param)
        return json.dumps(ret)
    except Exception as e:
        print(e)
        pass


@app.route("/getauth", methods=['GET', 'POST'])
@verify_token
def lg_getauth():
    '''
    获得权限模块
    输入(token默认输入)
    返回:ret集合,ret.code=200
    :return:
    '''
    try:
        param = get_param(request)
        ret = get_usermenu(param)
        return json.dumps(ret)
    except Exception as e:
        print(e)
        ret = deepcopy(g_ret)
        ret['code'] = 401
        ret['msg'] = 'token验证失败'
        return json.dumps(ret)


@app.route("/check_companybyguid", methods=['GET', 'POST'])
# @verify_token
def lg_check_companybyguid():
    '''
    获取公司列表
    输入(token默认输入): guid
    返回:ret集合,admin_bd角色返回所有公司列表,普通人员返回自己公司列表
    :return:
    '''
    LOG.info('通过GUID获取公司列表')
    param = get_param(request)
    ret = checkcompany_byguid(param.get('guid'))
    return json.dumps(ret)


@app.route("/check_companybycompanyname", methods=['GET', 'POST'])
# @verify_token
def lg_check_companybycompanyname():
    '''
    获取公司列表
    输入(token默认输入): company_name
    返回:ret集合,admin_bd角色返回所有公司列表,普通人员返回自己公司列表
    :return:
    '''
    LOG.info('通过公司名获取公司列表')
    param = get_param(request)
    ret = checkcompany_bycompanyname(param.get('company_name'))
    return json.dumps(ret)
